package com.voicechat.firstmet.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.voicechat.firstmet.MainActivity;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.client.WsManager;
import com.voicechat.firstmet.imcontrol.ILoginView;
import com.voicechat.firstmet.imcontrol.LoginHelper;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.LoginService;
import com.voicechat.firstmet.utils.MD5Utils;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity_imessage
 * @ClassName: LoginPassWordActivity
 * @Description: 登录输入密码页面
 * @Author: ljp
 * @CreateDate: 2018/8/30 15:18
 * @Version: 1.0
 */
public class LoginPassWordActivity extends BaseActivity implements View.OnClickListener, ILoginView {
    @BindView(R.id.et_pass_word)
    EditText etPassWord;
    @BindView(R.id.image_open)
    Button imageOpen;
    @BindView(R.id.tv_code_login)
    TextView tvCodeLogin;
    @BindView(R.id.login_sure)
    TextView loginSure;
    @BindView(R.id.tv_forget_pass)
    TextView tvForgetPass;
    @BindView(R.id.iv_back)
    LinearLayout ivBack;
    private boolean selected = false;
    //用户手机号码
    private String mobile;

    private String TAG = "LoginPassWordActivity";
    private String userId;
    private String userSig;

    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_login_password;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            this.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        initView();

    }

    private void initView() {
        Intent intent = getIntent();
        mobile = intent.getStringExtra("mobile");
        imageOpen.setOnClickListener(this);
        tvCodeLogin.setOnClickListener(this);
        loginSure.setOnClickListener(this);
        tvForgetPass.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        loginSure.setClickable(false);
        etPassWord.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String trim = s.toString().trim();
                if (!TextUtils.isEmpty(trim)) {
                    imageOpen.setVisibility(View.VISIBLE);
                } else {
                    imageOpen.setVisibility(View.GONE);
                }
                if(trim.length() >= 6){
                    loginSure.setClickable(true);
                    loginSure.setBackgroundResource(R.drawable.login_btn);
                }else {
                    loginSure.setClickable(false);
                    loginSure.setBackgroundResource(R.drawable.login_btn_2);
                }
            }
            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //显示隐藏密码
            case R.id.image_open:
                if (selected) {
                    imageOpen.setSelected(true);
                    selected = false;
                    // etPassWord.setInputType(InputType.TYPE_CLASS_TEXT);
                    etPassWord.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    etPassWord.setSelection(etPassWord.getText().toString().length());
                } else {
                    imageOpen.setSelected(false);
                    selected = true;
                    //etPassWord.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    etPassWord.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    etPassWord.setSelection(etPassWord.getText().toString().length());
                }
                break;
            //确定按钮   密码登录
            case R.id.login_sure:
                setLogin();
                break;
            //忘记密码
            case R.id.tv_forget_pass:
                Intent intent = new Intent(this, GetCodeActivity.class);
                intent.putExtra("mobile",mobile);
                intent.putExtra("flag","2");
                startActivity(intent);
                finish();
                break;
            //验证码登录
            case R.id.tv_code_login:
                Intent intent2 = new Intent(this, GetCodeActivity.class);
                intent2.putExtra("mobile",mobile);
                intent2.putExtra("flag","1");
                startActivity(intent2);
                finish();
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    /**
    * @method
    * @description 密码登录
    * @date: 2018/9/18 20:38
    * @author: ljp
    * @return
    */
    private void setLogin() {
        loginSure.setEnabled(false);
        String deviceInfo = PhoneUtils.getDeviceInfo(context);
        String passWord = etPassWord.getText().toString().trim();
        String md5PassWord = MD5Utils.getMd5Value(passWord);
        Log.i(TAG, "setLogin: ----------"+md5PassWord);
        if(!TextUtils.isEmpty(passWord)){
            LoginService.loginPassword(mobile,md5PassWord,deviceInfo).subscribe(mySelfInfoBean -> {

                if(mySelfInfoBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS){//登录成功，跳到主页
                    Log.i(TAG, "setLogin: ------"+mySelfInfoBean.getObject().toString());
                    MySelfInfoBean.ObjectBean object = mySelfInfoBean.getObject();
                    SPUtils.setEditorKeyValue(SPUtils.SP_PHONE,mobile);
                    SPUtils.setEditorKeyValue(SPUtils.SP_TOKEN,object.getToken());
                    SPUtils.setEditorKeyValue(SPUtils.SP_USERSIG,mySelfInfoBean.getMap().getUserSig());
                    SPUtils.setEditorKeyValue(SPUtils.SP_MYSELFINFO, ParcelableUtils.marshall(object));
                    //Log.i(TAG, "setLogin: ---mySelfInfoBean---"+mySelfInfoBean.getObject());
                    toast_MakeText("正在登陆中……");
                    WsManager.getInstance(context).init(mySelfInfoBean.getObject().getId());
                    //Log.i(TAG, "setLogin: ---mySelfInfoBean---"+mySelfInfoBean.getObject());
                    userId = object.getId();
                    userSig = mySelfInfoBean.getMap().getUserSig();
                    //Message message = Message.obtain();
                    //message.what = 1;
                   // handler.sendMessage(message);
                    LoginHelper loginHelper = new LoginHelper(this);
                    loginHelper.login(userId,userSig);
                   // removeAllActivity();
                   // Intent intent = new Intent(this, MainActivity.class);
                   // startActivity(intent);
                }else if(mySelfInfoBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_INFODATA){//用户未完善资料
                    MySelfInfoBean.ObjectBean object = mySelfInfoBean.getObject();
                    SPUtils.setEditorKeyValue(SPUtils.SP_PHONE,mobile);
                    SPUtils.setEditorKeyValue(SPUtils.SP_TOKEN,object.getToken());
                    SPUtils.setEditorKeyValue(SPUtils.SP_USERSIG,mySelfInfoBean.getMap().getUserSig());
                    SPUtils.setEditorKeyValue(SPUtils.SP_MYSELFINFO, ParcelableUtils.marshall(object));
                    Intent intent = new Intent(this, RegisterActivity.class);
                    intent.putExtra("mobile",mobile);
                    startActivity(intent);
                }else if(mySelfInfoBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_FAIL){
                    loginSure.setEnabled(true);
                    toast_MakeText("密码错误,请重新输入");
                }
            },throwable -> {
                Log.i(TAG, "setLogin: -----"+throwable.toString());
            });
        }
    }

    @Override
    public void updateLoginState(boolean state) {
        Log.i(TAG, "updateLoginState: -----"+state);
    }
    @Override
    public void onLoginSDKSuccess() {
        Log.i(TAG, "onLoginSDKSuccess: ---登录成功--");
        toast_MakeText("登录成功!");
        removeAllActivity();
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
    }
    @Override
    public void onLoginSDKFailed(int errCode, String errMsg) {
        loginSure.setEnabled(true);
        //loginHelper.login(userId,userSig);
        toast_MakeText("登录失败，请重试！");
        Log.i(TAG, "onLoginSDKFailed: --errMsg---"+errMsg);
        Log.i(TAG, "onLoginSDKFailed: --errCode---"+errCode);
    }
    @Override
    public void onLogoutSDKSuccess() {
        Log.i(TAG, "onLogoutSDKSuccess: -------");
    }

    @Override
    public void onLogoutSDKFailed(int errCode, String errMsg) {
        Log.i(TAG, "onLogoutSDKFailed: ----"+errMsg);

    }
}
